﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;

namespace wplCopy
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _FolderSelect.RootFolder = Environment.SpecialFolder.Desktop;

            _FileSelect.InitialDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), "Playlists");
            _FileSelect.FileName = String.Empty;
        }

        private void _OpenWPL_Click(object sender, EventArgs e)
        {
            if (_FileSelect.ShowDialog() == DialogResult.OK)
            {
                ParseFile(_FileSelect.FileName);
            }
        }

        private void ParseFile(String path)
        {
            _FileList.Items.Clear();

            XmlDocument xml = new XmlDocument();
            xml.Load(path);

            foreach (XmlNode xNode in xml.SelectNodes(@"smil/body/seq/media"))
            {
                _FileList.Items.Add(xNode.Attributes["src"].Value);
            }

            foreach (ListViewItem lvi in _FileList.Items)
                lvi.Checked = true;

            _FileList.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
        }

        private void _BrowseForOutputFolder_Click(object sender, EventArgs e)
        {
            if (_FolderSelect.ShowDialog() == DialogResult.OK)
            {
                _OutputFolder.Text = _FolderSelect.SelectedPath;
            }
        }

        private void _Copy_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(_OutputFolder.Text))
            {
                MessageBox.Show("Select output folder!");
                return;
            }
            if (_FileList.CheckedItems.Count < 1)
            {
                MessageBox.Show("Select something to copy!");
                return;
            }

            foreach (ListViewItem lvi in _FileList.CheckedItems)
            {
                String filename = lvi.Text;
                FileInfo file = new FileInfo(filename);

                if (file.Exists)
                {
                    file.CopyTo(Path.Combine(_OutputFolder.Text, file.Name), false);
                }
            }

            MessageBox.Show("Copy complete!");
        }
    }
}
